package util

import (
	"bufio"
	"fmt"
	"io"
	"net"
	"net/http"
	"os"
	"path/filepath"
	"time"
)

func DownloadFileFromUrl2(url, filename, dir string) error {

	fmt.Println(url)
	// 增加超时功能，否则 永久阻塞 就麻烦了。
	client := http.DefaultClient
	client.Timeout = time.Second * 10

	time.Sleep(5 * time.Second)

	res, err := client.Get(url)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	// 获得get请求响应的reader对象
	reader := bufio.NewReaderSize(res.Body, 32*1024)

	newFilename := filepath.Join(dir, filename)

	//newFilename := filepath.Join(test.imgPath,fmt.Sprintf("%d-%s",time.Now().Unix(),fileName))
	file, err := os.Create(newFilename)
	if err != nil {
		return err
	}
	defer file.Close()

	// 获得文件的writer对象
	writer := bufio.NewWriter(file)

	written, err := io.Copy(writer, reader)
	if err != nil {
		return err
	}
	err = writer.Flush()
	if err != nil {
		return err
	}

	if written <= 0 {
		return fmt.Errorf("空文件")
	}

	//fmt.Printf("Total length: %d", written)

	return nil
}

func DownloadFileFromUrl(url, filename, dir string) error {

	fmt.Println(url)
	// 增加超时功能，否则 永久阻塞 就麻烦了。
	client := &http.Client{
		Transport: &http.Transport{
			Dial: func(netw, addr string) (net.Conn, error) {
				conn, err := net.DialTimeout(netw, addr, time.Second*2)
				if err != nil {
					return nil, err
				}
				conn.SetDeadline(time.Now().Add(time.Second * 5))
				return conn, nil
			},
			ResponseHeaderTimeout: time.Second * 15,
		},
	}

	//time.Sleep(5 * time.Second)

	req, _ := http.NewRequest("GET", url, nil)

	//cookie1 := &http.Cookie{Name: "JSESSIONID", Value: "DF89DA9909D695F240203D67AE2F6E94"}
	//req.AddCookie(cookie1)

	// 设置请求投
	req.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
	req.Header.Add("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
	req.Header.Add("Connection", "keep-alive")
	req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36")
	req.Header.Add("Accept-Encoding", "gzip, deflate, br")
	req.Header.Add("Host", "www.nstl.gov.cn")

	res, err := client.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	// 获得get请求响应的reader对象
	reader := bufio.NewReaderSize(res.Body, 32*1024)

	newFilename := filepath.Join(dir, filename)

	//newFilename := filepath.Join(test.imgPath,fmt.Sprintf("%d-%s",time.Now().Unix(),fileName))
	file, err := os.Create(newFilename)
	if err != nil {
		return err
	}
	defer file.Close()

	// 获得文件的writer对象
	writer := bufio.NewWriter(file)

	written, err := io.Copy(writer, reader)
	if err != nil {
		return err
	}
	err = writer.Flush()
	if err != nil {
		return err
	}

	if written <= 0 {
		return fmt.Errorf("空文件")
	}

	//fmt.Printf("Total length: %d", written)

	return nil
}
